package com.renjian.funplaypro.controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.renjian.funplaypro.mappers.UserMessageMapper;
import com.renjian.funplaypro.model.User;
import com.renjian.funplaypro.model.UserMessage;
import com.renjian.funplaypro.services.UserMessageService;
import com.renjian.funplaypro.services.UserService;
import com.renjian.funplaypro.utils.CommonResult;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
public class UserMessageController {
    @Resource
    UserMessageService userMessageService;

    @Resource
    UserService userService;

    @Resource
    UserMessageMapper userMessageMapper;
    /**
     * @author renjian
     * @description 获取全部对话
     * @param msg
     * @return
     */
    @GetMapping("/msgs/get_all/{userId}/{type}")
    public Object getAllMsg(@PathVariable Long userId,@PathVariable Integer type){
        List<UserMessage> msgs = userMessageService.getAllMsgs(userId,type);
        msgs.forEach(item->{
            User user = userService.getById(userId == item.getFromUserId() ? item.getFromUserId() : item.getToUserId());
            item.setUser(user);
        });
        return new CommonResult().success(msgs);
    }

    @GetMapping("/msg/getUserMsgs")
    public Object getUserMsgs(Long fromUserId,Long toUserId,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date createTime){
        List<UserMessage> msgs = userMessageMapper.getUserMsgs(fromUserId,toUserId,createTime);
        msgs.forEach(msg->{
            if(msg.getFromUserId().equals(fromUserId)){
                msg.setUser(userService.getOne(new QueryWrapper<User>().eq("id",msg.getToUserId())));
            }else{
                msg.setUser(userService.getOne(new QueryWrapper<User>().eq("id",msg.getFromUserId())));
            }
        });
        return new CommonResult().success(msgs);
    }
}
